# !/usr/bin/env python
# encoding: utf-8
'''
  @author: HJW
  @license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
  @contact: hejunwang01@126.com
  @file: user.py
  @time: 2022/7/31 0031 下午 22:03
  @desc:
  '''


from  flask import Blueprint,request,jsonify
from models import MyUser
from sqlalchemy.orm import class_mapper
from utils.hashmd5 import MD5
from dbs import db
import logging
from utils.operadirectory import as_dict


# 注册的蓝图 ,url_prefix 在所有的路径前面增加/user
bp = Blueprint('user',__name__,url_prefix='/user')
logger = logging.getLogger(__name__)

@bp.route('/v1/login',methods=['POST'])
def login():
    if request.method == "POST":
        # axios中 使用payload的方式进行请求带参, 所以选哟使用reques.json.get这种方式来获取里面的带入的参数
        in_name =request.json.get("name")
        in_passwd =request.json.get("passwd")

        print("传入的name:{}".format(in_name))
        print("传入的passwd:{}".format(in_passwd))
        res = MyUser.query.filter_by(name= in_name,passwd = MD5().set_md5(in_passwd)).all()
        print(res)
        if len(res) :
            data_list = []
            for item in res:
                data_list.append(as_dict(item))
            ret =data_list[0]
            print("返回的结果name:",ret['name'])
            print("返回的结果解密后passwd:",ret['passwd'])
            # 校验数据库中的用户名和密码是否正确
            if (ret['name'] ==in_name) and (ret['passwd']==MD5().set_md5(in_passwd)):
                # 登录成功后,给客户端发送token
                logger.info('token:',"generate_auth_token(in_name)")
                return jsonify({'code': 200, "msg": "登录成功!","token":"generate_auth_token(in_name)"})
            else:
                return jsonify({"code": -1, "msg": "account or password is wrong!"})
        else:
            # return render_template('index.html')
            return jsonify({"code":-1,"msg":"account or password is wrong!"})
    else:
        return jsonify({"code":-100,"msg":"request 请求方式错误!"})



@bp.route('/v1/logout',methods=['POST'])
def logout():
    name = request.json.get("name")
    if name :
        return jsonify({"code":200,"msg":"退出成功"})
    else:
        return jsonify({"code":401,"msg":"退出失败"})




# 分页查询获取列表
@bp.route('/v1/userlist.json',methods=['POST'])
def getuserlist():
    in_pagesize = request.json.get("pagesize")
    in_pagenum = request.json.get("pagenum")
    print("in_pagesize 第X页数量--> {}".format(in_pagesize))
    print("in_pagenum 第X页数--> {}".format(in_pagenum))
    # 分页查询  ,查询第2页的数据,每页3个  基于Sqlalchemy 实现的分页器 QueryPaginate
    pn = MyUser.query.paginate(page=in_pagenum,per_page=in_pagesize,error_out=True)
    # pn.items 获取到该页的数据 ,pn.page获取当前的页码 ,pn.page获取总页数
    collections  = pn.items
    print(collections)
    print(type(collections))
    # 获取当前页码
    current_page = pn.page
    # 获取总页数
    total_page = pn.pages
    data_list = []
    for item in collections:
        data_list.append(as_dict(item))

    total = MyUser.query.count()
    print("total:{}".format(total))
    return jsonify({"code":200,"res":data_list,'total':total})


#查询 模糊搜索 查询用户,user
@bp.route('/v1/searchuser.json',methods=['POST'])
def searuser():
    if request.method=="POST":
        in_query = request.json.get("query")
        searchcontain = MyUser.query.filter(MyUser.name.contains(in_query)).all()
        print(searchcontain)
        data_list = []
        for item in searchcontain:
            data_list.append(as_dict(item))

        return jsonify({"code":200,"res":data_list,"total":len(data_list)})
    else:
        return jsonify({"code": -1, "res": "请求方法错误"})



# 添加 管理员 user
@bp.route('/v1/adduser.json',methods=['POST'])
def adduser():
    name = request.json.get('name')
    passwd = request.json.get('passwd')
    role = request.json.get('role')
    print(name,passwd,role)
    # 查询数据库中有没有这个name ,如果有, 就提示已经有了 ,如果没有 ,新增加一个
    query = MyUser.query.filter_by(name=name).all()
    if len(query):
        return jsonify({"code":-1 ,"message":"该用户名已经存在!"})
    else:
        try:
            # 创建对象
            newuser=MyUser(name=name,passwd=MD5().set_md5(passwd),role=role,status = True)
            # session记录对象任务
            db.session.add(newuser)
            # 提交任务到数据库中
            db.session.commit()
            return jsonify({"code":200,"message":"添加成功!"})
        except Exception as e:
            db.session.rollback()  # 事务回滚
            return jsonify({"code":-1,"message":"添加失败 !"})

# 删除管理员账户
@bp.route('/v1/deleteuser.json',methods=['POST'])
def deleteuser():
    name = request.json.get('name')
    print('will delete name :{}'.format(name))
    try:
        MyUser.query.filter_by(name = name).delete()
        db.session.commit()
        return jsonify({"code":200,"message":"删除成功!"})
    except Exception as e :
        db.session.rollback()  # 事务回滚

        return jsonify({"code": -1, "message": "删除失败! 原因:{}".format(str(e))})


# 修改用户的状态
@bp.route('/v1/update/userstatus.json',methods=['PUT'])
def userstatus():
    name = request.json.get('name')
    status = request.json.get('status')
    print(name,status)
    try:
        MyUser.query.filter_by(name=name).update({'status':status })
        db.session.commit()
        return jsonify({"code":200,'msg':"更新用户状态成功!"})

    except Exception as e :
        db.session.rollback()  # 事务回滚
        return jsonify({"code":-1,'msg':"更新用户状态失败!"})
